package org.dromara.common.core.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

public class EntityCopyUtils {

    /**
     * 实体复制
     * 把src中不为NULL的字段，复制给target
     *
     * @param src    要复制的类实体
     * @param target 最后得到的实体
     */
    public static void copyPropertiesIgnoreNull(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }


    private static String[] getNullPropertyNames(Object source) {
        BeanWrapperImpl beanWrapperImpl = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = beanWrapperImpl.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = beanWrapperImpl.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.<String>toArray(result);
    }
}
